﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Mammoth.Services
{
    public static class ConfigurationController
    {
        public static void SaveConfiguration(this ConfigurationSection section, string sectionName, bool encrypted = false)
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.Sections.Count > 0)
            {
                config.Sections.Remove(sectionName);
            }
            ConfigurationSection newSection = (ConfigurationSection)((ICloneable)section).Clone();
            config.Sections.Add(sectionName, newSection);
            if(encrypted)
                newSection.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
            config.Save();
        }

        public static T Load<T>(string sectionName) where T : ConfigurationSection, new()
        {
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            try
            {
                var section = config.GetSection(sectionName);
                if (section != null)
                {
                    if(section.SectionInformation.IsProtected)
                        section.SectionInformation.UnprotectSection();
                    return (T)section;
                }
                else
                    return new T();
            }
            catch (Exception)
            {
                return new T();
            }
        }
    }
}
